package com.flybear.aqi.server;

import com.google.common.collect.Maps;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

public class CustomerDecoder extends MessageToMessageDecoder<ByteBuf> {

    // TODO Use CharsetDecoder instead.
    private final Charset charset;

    /**
     * Creates a new instance with the current system character set.
     */
    public CustomerDecoder() {
        this(Charset.defaultCharset());
    }

    /**
     * Creates a new instance with the specified character set.
     */
    public CustomerDecoder(Charset charset) {
        if (charset == null) {
            throw new NullPointerException("charset");
        }
        this.charset = charset;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        out.add(parseKV(msg.toString(charset),6));
    }

    private static Map<String,String> parseKV(String value, int off) {
        Map<String, String> map = Maps.newLinkedHashMap();
        char[] in = value.toCharArray();
        char aChar;
        int len=value.length();
        int end = len - 6;
        char[] out = new char[len];
        int outLen = 0;
        String key = "";
        while (off < end) {
            aChar = in[off++];
            if ((aChar == '=')) {
                key = new String(out, 0, outLen);
                outLen = 0;
            } else if (aChar == ';' || aChar == ',') {
                String val = new String(out, 0, outLen);
                outLen = 0;
                map.put(key, val);
            } else if (aChar == '&') {
                //ignore &
            } else if (aChar == 'C') {
                aChar = in[off++];
                if (aChar == 'P') {
                    aChar = in[off++];
                    if (aChar == '=') {

                    } else {
                        out[outLen++] = 'C';
                        out[outLen++] = 'P';
                    }
                } else {
                    out[outLen++] = 'C';
                }
            } else {
                out[outLen++] = aChar;
            }
        }
        return map;
    }
}